import * as echarts from '../../ec-canvas/echarts';
let globalChart = null;
Page({
  data: {
    todayfood: 100,
    weekfood: 700,
    ec: {
      onInit: initChart
    },
    selectedButtonIndex: 0,
    selectedRange: '本周',
    color1:'#FCFCFC',
    color2:'#54A3FA',
    color3:'#FCFCFC',
    color4:'#54A3FA',
    color5:'#FCFCFC',
    color6:'#54A3FA',
  },
  getXAxisData: function (range) {
    if (range === '本周') {
      return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    } else if (range === '本月') {
      return ['第一周', '第二周', '第三周', '第四周'];
    } else if (range === '本季度') {
      return ['第一月', '第二月', '第三月'];
    }
  },
  
  switchData: function (event) {
    const range = event.currentTarget.dataset.range;
    this.setData({
      selectedRange: range,
    });
    if (globalChart) {
      globalChart.setOption({
        title: {
          text: range + '喂食量/g',
        },
      });
      const xAxisData = this.getXAxisData(range);
      globalChart.setOption({
        xAxis: {
          data: xAxisData,
        },
      });
    }
    if(range=='本周')
    {
      this.setData({
      color1:'#54A3FA',
      color2:'#FCFCFC',
      color3:'#FCFCFC',
      color4:'#54A3FA',
      color5:'#FCFCFC',
      color6:'#54A3FA',})
    }
    else if(range == '本季度')
    {
      this.setData({
      color1:'#FCFCFC',
      color2:'#54A3FA',
      color3:'#FCFCFC',
      color4:'#54A3FA',
      color5:'#54A3FA',
      color6:'#FCFCFC',})
    }
    else if(range == '本月')
    {
      this.setData({
      color1:'#FCFCFC',
      color2:'#54A3FA',
      color3:'#54A3FA',
      color4:'#FCFCFC',
      color5:'#FCFCFC',
      color6:'#54A3FA',
      })
    }
  },
})

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });

  canvas.setChart(chart);

  const option = {
    title: {
      text: '本周喂食量/g',
      left: 'center',
      top: 20,
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }]
  };

  globalChart = chart; // 将 chart 赋值给全局变量

  chart.setOption(option);
  return chart;
}
